package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-master/cache"
	"novel-master/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))

	Offset := (page - 1) * size

	var novels []models.Novels

	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(Offset).Limit(size).Find(&novels)

		jsonData, _ := json.Marshal(novels)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novels)
	}

	var total int64
	models.DB.Model(&models.Novels{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  novels,
		"total": total,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var novels models.Novels

	redis_key := "novel_select_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Debug().First(&novels)

		jsonData, _ := json.Marshal(novels)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novels)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": novels,
	})
	return
}
